package com.fmdj.nebula.service.impl;

import cn.hutool.core.map.MapUtil;
import com.fmdj.nebula.controller.vo.InsertOrderGpsVo;
import com.fmdj.nebula.db.dao.OrderGpsDao;
import com.fmdj.nebula.service.OrderGpsService;
import com.fmdj.nebula.util.LocationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.util.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;

@Service
@Slf4j
public class OrderGpsServiceImpl implements OrderGpsService {

    @Autowired
    private OrderGpsDao orderGpsDao;

    @Autowired
    private LocationUtil locationUtil;

    @Override
    public int insertOrderGps(ArrayList<InsertOrderGpsVo> list) {
//        int rows = 0;
//        for (InsertOrderGpsVo entity : list) {
//            rows += orderGpsDao.insert(entity);
//        }
        return list.stream().mapToInt(orderGpsDao::insert).sum();  //将集合中的元素转换成int流，并求和
    }

    @Override
    public ArrayList<HashMap> searchOrderGps(long orderId) {
        ArrayList<HashMap> list = orderGpsDao.searchOrderGps(orderId);
        return list;
    }

    @Override
    public HashMap searchOrderLastGps(long orderId) {
        HashMap hashMap = orderGpsDao.searchOrderLastGps(orderId);
        return hashMap;
    }

    @Override
    public String calculateOrderMileage(long orderId) {
        //获取所有的GPS
        ArrayList<HashMap> list = orderGpsDao.searchOrderAllGps(orderId);  //将拿到的经纬度封装在了hashMap中 一个个hashMap(经纬度)封装在列表中
        //计算从开始到结束GPS之间的距离 两点之间计算
        double mileage = 0;
        for (int i = 0; i < list.size(); i++) {
            if (i!=list.size()-1) {
                HashMap map_1 = list.get(1);
                HashMap map_2 = list.get(i+1);
                Double latitude_1 = MapUtil.getDouble(map_1, "latitude");
                Double longitude_1 = MapUtil.getDouble(map_1, "longitude");
                Double latitude_2 = MapUtil.getDouble(map_2, "latitude");
                Double longitude_2 = MapUtil.getDouble(map_2, "longitude");
                double distance = locationUtil.getDistance(latitude_1, longitude_1, latitude_2, longitude_2);
                mileage += distance;
            }
        }
        return mileage + "";
    }

}
